import { NextResponse } from 'next/server';
import prisma from '@/lib/prisma';
import { getUser } from '@/lib/authUtils';

// 更新字幕
export async function PUT(
  request: Request,
  { params }: { params: { id: string } }
): Promise<Response> {
  const userid = await getUser(request);
  if (!userid) {
    return NextResponse.json(
      { error: '未授权或登录信息过期，请登录' },
      { status: 401 }
    );
  }
  if (userid instanceof NextResponse) {
    return userid;
  }
  try {
    const { id } = params;
    const body = await request.json();

    // 更新字幕内容
    const updatedSubtitle = await prisma.vms_asr.update({
      where: { id },
      data: {
        subtitle_text: body.subtitle_text,
      }
    });

    // 返回更新后的字幕
    return NextResponse.json({
      ...updatedSubtitle,
      id: updatedSubtitle.id.toString(),
      task_id: updatedSubtitle.task_id?.toString()
    });

  } catch (error) {
    console.error('Failed to update subtitle:', error);
    return NextResponse.json(
      { error: 'Failed to update subtitle' },
      { status: 500 }
    );
  }
}

// 删除字幕
export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
): Promise<Response> {
  try {
    const { id } = params;

    // 删除字幕记录
    await prisma.vms_asr.delete({
      where: { id }
    });

    return new Response(null, { status: 204 });

  } catch (error) {
    console.error('Failed to delete subtitle:', error);
    return NextResponse.json(
      { error: 'Failed to delete subtitle' },
      { status: 500 }
    );
  }
}